package com.lanyou.esb.web;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import org.apache.commons.lang3.StringUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**
 * @author 陈龙涛
 *
 */
public class RestAPI {
	
	public static final String AUTHOR = "karaf:karaf";
	public static final String NODE_URL_SUFFIX = "/hawtio/jolokia/read/org.apache.karaf.cellar:type=node,name=root/Nodes";
	public static final String CPU_URL_SUFFIX = "/hawtio/jolokia/read/java.lang:type=OperatingSystem/SystemCpuLoad";
	public static final String FREE_MEMORY_URL_SUFFIX = "/hawtio/jolokia/read/java.lang:type=OperatingSystem/FreePhysicalMemorySize";
	public static final String TOTAL_MEMORY_URL_SUFFIX = "/hawtio/jolokia/read/java.lang:type=OperatingSystem/TotalPhysicalMemorySize";
	
	/**
	 * 用GET请求获取REST API的内容
	 * @param username 请求头的认证名
	 * @param password 请求头的认证密码
	 * @param restURL 请求的REST URL地址
	 * @return 返回请求的内容
	 */
	public static String requestByGetMethod(String ipaddr, String port , String flag) {
		String restURL = "";
		if("NODE".equals(flag)){	//节点请求地址
			restURL = "http://" + ipaddr +":" + port + NODE_URL_SUFFIX;
		}else if ("CPU".equals(flag)){	//CPU请求地址
			restURL = "http://" + ipaddr +":" + port + CPU_URL_SUFFIX;
		}else if ("MEMORY".equals(flag)){	//空闲内存请求地址
			restURL = "http://" + ipaddr +":" + port + FREE_MEMORY_URL_SUFFIX;
		}else if ("TOTALMEMORY".equals(flag)){	//总内存请求地址
			restURL = "http://" + ipaddr +":" + port + TOTAL_MEMORY_URL_SUFFIX;
		}
		String authorEncoding = Base64.getEncoder().encodeToString(AUTHOR.getBytes());	//对请求头的用户名和密码使用BASE64加密
		
		String content = "";
		HttpURLConnection conn = null;
		InputStream is = null;
		try {
			URL url = new URL(restURL);	//创建URL			
			conn = (HttpURLConnection) url.openConnection();	//开启连接
			conn.setRequestMethod("GET");	//设置请求方式为GET请求
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setRequestProperty("Content-Type","application/json");	//设置请求格式
			conn.setRequestProperty("Authorization", "Basic " + authorEncoding);	//设置请求认证
			conn.setConnectTimeout(70);	//设置连接超时
			conn.setReadTimeout(100); 	//设置读取超时
			
			is = conn.getInputStream();			
			byte[] buff=new byte[1024];
			int len=0;
			while((len=is.read(buff))!=-1){	//读取数据
				String ss = new String(buff,0,len,"UTF-8");
				content += ss;
			}
			
		} catch (Exception e) {
			return "false";
		} finally{
			if(is != null){
				try {
					is.close();//关闭连接，释放资源
				} catch (IOException e) {
					e.printStackTrace();
				}			
			}
			conn.disconnect();			
		}
		return content;
	}
		
	/**
	 * 从JSON字符串中解析出CPU的使用率
	 * @param cpujson
	 * @return
	 */
	public static double getCPU(String cpujson){
		//如果cpujson为false说明本次请求出错，直接返回0
		if(StringUtils.equals(cpujson, "false")){
			return 0;
		}
		JsonObject jsonObject = new JsonParser().parse(cpujson).getAsJsonObject();
		double cpuinfo = jsonObject.get("value").getAsDouble();
		return cpuinfo * 100;
	}

	/**
	 * 从JSON字符串中解析出物理内存信息
	 * @param memoryJson
	 * @return
	 */
	public static double getMemory(String memoryjson) {
		//如果memoryjson为false说明本次请求出错，直接返回0
		if(StringUtils.equals(memoryjson, "false")){
			return 0;
		}
		JsonObject jsonObject = new JsonParser().parse(memoryjson).getAsJsonObject();
		double memoryInfo = jsonObject.get("value").getAsDouble();
		return memoryInfo;
	}
}
